'use strict';
const Package = require('@imooc-my-test1/package')
const log = require('@imooc-my-test1/log')
const { Spawn } = require('@imooc-my-test1/utils')
const path = require('path');
const colors = require('colors')

module.exports = exec;

// 后期可以用接口
const SETTINGS = {
  init: '@imooc-cli/init'
  // init: '@imooc-my-test1/core'
}
const CACHE_PATH = 'dependencies'

async function exec() {
  let targetPath = process.env.CLI_TARGET_PATH;
  let homePath = process.env.CLI_HOME_PATH;
  let storePath; 
  let pkg;
  log.verbose('homePath', homePath)
  log.verbose('targetPath', targetPath)
  const commandItem = arguments[arguments.length - 1];
  const packageName = SETTINGS[commandItem.name()];
  const packageNameVersion = 'latest'

  if(!targetPath) {
    targetPath = path.resolve(homePath, CACHE_PATH)
    storePath = path.resolve(targetPath, 'node_modules')
    pkg = new Package({
      packageName,
      storePath,
      packageNameVersion,
      targetPath
    });
    if(await pkg.exists()) {
      await pkg.update()
    } else {
      // await pkg.install()
    }
  } else {

    pkg = new Package({
      packageName,
      packageNameVersion,
      targetPath
    })
  }

  const filePath = pkg.getRootFilePath();

  if(filePath) {
    try {
      const args = Array.from(arguments);
      const o = Object.create(null);
      const cmd = args[args.length - 1];
      Object.keys(cmd).forEach(item => {
        if(cmd.hasOwnProperty(item) && !item.startsWith('_') && item!=='parent') {
          o[item] = cmd[item]
        }
      })
      args[args.length - 1] = o
      let code = `require("${filePath}").call(null, ${JSON.stringify(args)})`
      const child = Spawn('node', ['-e', code], {
        cwd: process.cwd(),
        stdio: 'inherit',
      })

      child.on('error', e => {
        log.error(e.message)
        process.exit(1)
      })

      child.on('exit', e => {
        log.verbose('命令执行成功'+e)
        process.exit(e)
      })
    } catch (error) {
      log.error(colors.red(error.message))
    }
  }

  // function spawn(command, args, options) {
  //   const win32 = process.platform === 'win32';
  //   const cmd = win32 ?  'cmd' : command;
  //   const cmdArgs = win32 ? ['/c'].concat(command, args) : args;
  //   return cp.spawn(cmd, cmdArgs, options || {})
  // }

  // const params = {
  //   targetPath,
  // }
  // const pkg = new Package({
  //   packageName,
  //   storePath,
  //   packageNameVersion,
  //   targetPath
  // });

  // console.log(pkg.getRootFilePath(), 'jjjj0-00')
}